package stanpayng

import (
	"context"
	"errors"

	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/xerrors/assets"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/stanPaysNg"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/bytedance/sonic"
	"github.com/zeromicro/go-zero/core/logc"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type StanPayNgPayoutNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// stanpayng提现回调通知
func NewStanPayNgPayoutNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *StanPayNgPayoutNotifyLogic {
	return &StanPayNgPayoutNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *StanPayNgPayoutNotifyLogic) StanPayNgPayoutNotify(req *types.StanPayNgDisbursementCallbackRequest) (resp string, err error) {
	b, _ := sonic.Marshal(req)
	order, err := l.svcCtx.AssetsRpc.PayWithdraw.WithdrawListPage(l.ctx, &rpc.FindWithDrawReq{OrderNo: req.MchOrderNum})
	if err != nil {
		return
	}
	if len(order.Data) == 0 {
		logc.Error(l.ctx, "order.Data does not exist", string(b))
		err = assets.ErrWithdrawPayNoChannel
		return
	}
	if _, ok := order.Data[0].Channel[order.Data[0].WithdrawChannelId]; !ok {
		logc.Error(l.ctx, "order.Data[0].Channel[order.Data[0].WithdrawChannelId] does not exist", string(b))
		err = assets.ErrWithdrawPayNoChannel
		return
	}
	pubKey := order.Data[0].Channel[order.Data[0].WithdrawChannelId].GetPubKey()
	verify, err := stanPaysNg.NewStanPayNg(req.MchId).SetPublicKey(pubKey).DisbursementCallbackVerify(string(b))
	if err != nil {
		logc.Error(l.ctx, err)
		return
	}
	if !verify {
		logc.Error(l.ctx, "signature verification failed: ")
		err = errors.New("signature verification failed")
		return
	}
	// 根据订单状态处理业务逻辑
	if req.NotifyCode == stanPaysNg.ResponseCodeSUCCESS {
		_, err = l.svcCtx.AssetsRpc.PayWithdraw.WithdrawSuccess(l.ctx, &rpc.SuccessWithDrawReq{OrderNo: req.MchOrderNum, Data: string(b)})
	} else {
		_, err = l.svcCtx.AssetsRpc.PayWithdraw.WithdrawFail(l.ctx, &rpc.FailWithDrawReq{OrderNo: req.MchOrderNum, Data: string(b), Err: req.NotifyDesc})
	}
	if err != nil {
		logc.Error(l.ctx, err, string(b))
	}

	return
}
